<template>
  <div class="app-container">
    <el-row class="row bg-white">
      <div class="action">
        <div class="chart-filter">
          <el-button class="green-btn w-100" size="small" type="primary" v-if="btnUserAdd" @click="handleCreate" >新增用户</el-button>
          <!--<el-button class="green-btn w-100" size="small" type="primary" >下载报表<i class="el-icon-download el-icon&#45;&#45;right"></i></el-button>-->
          <div class="filter-right">
            <el-select  size="small" class="w-150" v-model="listQuery.status" filterable placeholder="用户状态">
              <el-option v-for="item in  statusOptions" :key="item.key" :label="item.text" :value="item.key">
              </el-option>
            </el-select>
            <el-select size="small" class="w-150" v-model="listQuery.review_status" filterable placeholder="业务状态">
              <el-option v-for="item in  reviewStatusOptions" :key="item.key" :label="item.text" :value="item.key">
              </el-option>
            </el-select>
            <el-date-picker
              v-model="date_pick_date"
              :editable="false"
              size="small"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
            <el-input type="text" class="w-180"   size="small"  v-model="listQuery.filter" placeholder="输入手机号码或姓名"></el-input>
            <el-button type="primary" class="green-btn" size="small" @click = 'handleFilter'>查询</el-button>
          </div>

        </div>
      </div>
      <el-table :data="list"  element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column label='时间' align="center">
          <template slot-scope="scope">
            {{scope.row.created_at}}
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">
            {{scope.row.name}}
          </template>
        </el-table-column>
        <el-table-column label="机构类型" align="center">
          <template slot-scope="scope">
            {{scope.row.group_name}}
          </template>
        </el-table-column>
        <el-table-column label="身份证号码" align="center">
          <template slot-scope="scope">
            {{scope.row.idcard}}
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center">
          <template slot-scope="scope">
            {{scope.row.phone}}
          </template>
        </el-table-column>
        <el-table-column label="营业执照" align="center">
          <template slot-scope="scope">
            <img v-if="scope.row.license !== ''" :src="scope.row.license" width="50" height="50" >
          </template>
        </el-table-column>
        <el-table-column label="业务状态" align="center">
          <template slot-scope="scope">
            {{scope.row.review_status_str}}
          </template>
        </el-table-column>
        <el-table-column label="用户状态" align="center">
          <template slot-scope="scope">
            {{scope.row.status_str}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <router-link v-if="scope.row.review_status==2 && btnReview"  class="link-type" :to="'/user/view/'+scope.row.user_id">
              <el-button type="primary" size="mini" class="green-btn-min" >审核</el-button>
            </router-link>
            <el-button v-if="scope.row.status==0 && btnStatusChange" type="primary" size="mini" class="green-btn-min"  @click="handleEnable(scope.row)">启用</el-button>
            <el-button v-else-if="scope.row.status==1 && btnStatusChange" type="primary" size="mini" class="green-btn-min"  @click="handleEnable(scope.row)">禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-row>
    <el-dialog
      title="新增用户"
      :visible.sync="showDialog"
      width="25%"
      center>
      <el-form center :model="userForm"  ref="userForm" :rules="userRules" label-position="left" label-width="120px">
        <el-form-item label="手机号码"  prop="phone" >
          <el-input size="small" v-model="userForm.phone" style="width: 230px;"></el-input>
        </el-form-item>
        <el-form-item label="用户名"  prop="username" >
          <el-input size="small" v-model="userForm.username" style="width: 230px;"></el-input>
        </el-form-item>
        <el-form-item label="用户组" prop="group_id" >
          <el-select  size="small" style="width: 230px;"  v-model="userForm.group_id" filterable placeholder="选择用户组">
            <el-option v-for="item in  groupOptions" :key="item.id" :label="item.group_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录密码" prop="password" >
          <el-input type="password"  size="small" placeholder="请输入密码" style="width: 230px;" v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass" >
          <el-input type="password"  size="small" placeholder="确认密码" style="width: 230px;" v-model="userForm.checkPass"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createUser">确 定</el-button>
        <el-button @click="showDialog=false">取 消</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
  import { validateMobile } from '@/utils/validate'
  import { fetchList, editStatus, groupList, store } from '@/api/user'
  import { in_array } from '@/utils/index'

  // 1审核通过，2审核中，3审核不通过
  export default {
    name: 'user',
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!validateMobile(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          if (this.userForm.checkPass !== '') {
            this.$refs.userForm.validateField('checkPass')
          }
          callback()
        }
      }
      var validatePass1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.userForm.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        list: [],
        total: null,
        listLoading: true,
        listQuery: {
          status: '',
          review_status: '',
          page: 1,
          pageSize: 20,
          filter: ''
        },
        statusOptions: [
          { key: 1, text: '启用' },
          { key: 0, text: '禁用' }
        ],
        reviewStatusOptions: [
          { key: 1, text: '审核通过' },
          { key: 2, text: '审核中' },
          { key: 3, text: '审核不通过' }
        ],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now()
          }
        },
        groupOptions: [],
        date_pick_date: '',
        showDialog: false,
        userForm: {
          'phone': '',
          'username': '',
          'password': '',
          'checkPass': '',
          'group_id': ''
        },
        userRules: {
          phone: [{ required: true, message: '请输入正确的手机号', trigger: 'blur', validator: validatePhone }],
          username: [{ required: true, message: '请输入用户名(2-15字符)', trigger: 'blur' },
            { min: 2, max: 15, message: '请输入用户名(2-15字符)', trigger: 'blur' }],
          password: [{ required: true, trigger: 'blur', validator: validatePass }],
          checkPass: [{ required: true, trigger: 'blur', validator: validatePass1 }],
          group_id: [{ required: true, message: '请选择用户组', trigger: 'change' }]
        },
        btnUserAdd: false,
        btnReview: false,
        btnStatusChange: false
      }
    },
    created() {
      this.getButtonStatus()
      this.getList()
      this.getGroupList()
    },
    methods: {
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      handleCreate() {
        this.showDialog = true
      },
      getList() {
        this.listLoading = true
        const data = {}
        data.userid = 3
        fetchList(this.listQuery).then(response => {
          if (response.code === 1) {
            this.list = response.data.list
            this.total = response.data.total
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          }
        })
      },
      getGroupList() {
        groupList().then(response => {
          if (response.code === 1) {
            this.groupOptions = response.data
          }
        })
      },
      createUser() {
        this.$refs.userForm.validate(valid => {
          if (valid) {
            store(this.userForm).then(response => {
              if (response.code === 1) {
                this.$message({
                  title: '成功',
                  message: '创建成功！',
                  type: 'success',
                  duration: 3000
                })
                this.showDialog = false
                this.getList()
                this.$refs.userForm.resetFields()
              }
            })
          }
        })
      },
      handleEnable(row) {
        var strMsg = ''
        var strStatus = ''
        const data = {}
        data.userid = row.user_id
        if (row.status === 0) {
          data.status = 1
          strMsg = '启用成功'
          strStatus = '启用'
        } else if (row.status === 1) {
          data.status = 0
          strMsg = '禁用成功'
          strStatus = '禁用'
        }
        editStatus(data).then(response => {
          if (response.code === 1) {
            for (const v of this.list) {
              if (v.id === row.id) {
                const index = this.list.indexOf(v)
                row.status = data.status
                row.status_str = strStatus
                this.list.splice(index, 1, row)
                break
              }
            }
            this.$message({
              title: '成功',
              message: strMsg,
              type: 'success',
              duration: 3000
            })
          } else {
            setTimeout(() => {
              this.$message.error(response.msg)
            }, 3 * 1000)
          }
        })
      },
      handleFilter() {
        this.getList()
      },
      getButtonStatus() {
        const btnList = this.$store.getters.buttons
        if (in_array('userAdd', btnList)) {
          this.btnUserAdd = true
        }
        if (in_array('userReview', btnList)) {
          this.btnReview = true
        }
        if (in_array('enable_disable', btnList)) {
          this.btnStatusChange = true
        }
      }
    }
  }
</script>
